package com.ruoyi.web.controller.wx_driver;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.WXConstants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.vqms.domain.VQMSDriver;
import com.ruoyi.vqms.service.IVQMSDriverService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import sun.applet.Main;

import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;

@RestController
@RequestMapping("/wx/driver")
public class LoginController {
    private static final Logger logger = Logger.getLogger(Main.class.getName());

    @Autowired
    private IVQMSDriverService driverService;
    @Autowired
    private SysLoginService loginService;
    @Autowired
    private RedisCache redisCache;

    /**
     * 修改个人信息（司机）
     */
    @Log(title = "修改个人信息（司机）", businessType = BusinessType.UPDATE)
    @PutMapping(value = "/update")
    public AjaxResult update(@RequestBody VQMSDriver vqmsDriver)
    {
        vqmsDriver.setUpdateBy(vqmsDriver.getPhone());
        driverService.update(vqmsDriver);
        return AjaxResult.success();
    }

    /**
     * 微信一键登陆
     */
    @PostMapping("/driver_login")
    public AjaxResult wxLogin_driver(@RequestBody Map<String,String> params){
        //获取用户授权信息
        String url="https://api.weixin.qq.com/sns/jscode2session?appid="+ WXConstants.APPID+
                "&secret="+WXConstants.SECRET+
                "&js_code="+params.get("wxCode")+"&grant_type=authorization_code";
        JSONObject result=JSONObject.parseObject(HttpUtils.sendGet(url,null));
        System.out.println("请求结果----》"+result.toString());

        if(result.get("openid") == null){
            logger.severe("openid为空-获取用户信息失败");
//            return AjaxResult.error("获取用户信息失败");
        }

        VQMSDriver vqmsDriver = new VQMSDriver();
        vqmsDriver.setPhone(params.get("phone"));
        List<VQMSDriver> list=driverService.selectList(vqmsDriver);
        System.out.println("新司机--"+list.isEmpty());
        if (list.isEmpty()){    //新司机
            if (result.get("openid") != null){
                vqmsDriver.setWxOpenId(result.get("openid").toString());
            }
            vqmsDriver.setWxName(params.get("nickName"));
            vqmsDriver.setCreateBy(params.get("phone"));
            int add = driverService.add(vqmsDriver);
            if (add != 1){
                return AjaxResult.error("访客新增失败");
            }
        }
//        重新查询，排除司机为空
        VQMSDriver vqmsDriver1 = driverService.getByPhone(vqmsDriver.getPhone());
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
//        String token = loginService.wxLoginDriver(WXConstants.DEFAULT_USERNAME, WXConstants.DEFAULT_PASSWORD,"微信用户",params.get("phone"));
        String token = loginService.wxLogin(WXConstants.DEFAULT_USERNAME, WXConstants.DEFAULT_PASSWORD);
        redisCache.setCacheObject("App-Token", token, 30, TimeUnit.DAYS);     //token存redis,7天过期

        ajax.put(Constants.TOKEN, token);
        ajax.put("phone",params.get("phone"));
//        ajax.put("wxName",vqmsDriver1.getWxName());
        ajax.put("driverId",vqmsDriver1.getId());
        ajax.put("name",vqmsDriver1.getName());
        ajax.put("openId",result.get("openid"));
        ajax.put("licensePlate",vqmsDriver1.getLicensePlate());

        return ajax;
    }

    /**
     * 微信获取手机号
     * @return
     */
    @RequestMapping("/getPhone")
    public AjaxResult getPhone(@RequestBody String code){
        //1.用appid和密钥获取access_token
        String tokenUrl="https://api.weixin.qq.com/cgi-bin/token";
        String params="grant_type=client_credential&appid=" + WXConstants.APPID + "&secret=" + WXConstants.SECRET;
        JSONObject tokenResult=JSONObject.parseObject(HttpUtils.sendGet(tokenUrl,params));
        System.out.println("获取信息1==》"+tokenResult.toString());
        if(tokenResult.get("errcode")!=null){
            return AjaxResult.error("获取手机号失败");
        }
        String accessToken=tokenResult.getString("access_token");

        //2.用access_token获取手机号
        JSONObject body = new JSONObject();
        body.put("code",code);
        String phoneUrl="https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + accessToken;
        JSONObject phoneResult =JSONObject.parseObject(HttpUtils.sendPost(phoneUrl,body.toString()));
        System.out.println("获取信息2==》"+phoneResult.toString());
        if(phoneResult.getInteger("errcode")!=0){
            return AjaxResult.error("获取手机号失败");
        }
        String phone = phoneResult.getJSONObject("phone_info").get("phoneNumber").toString();
        AjaxResult ajax = AjaxResult.success();
        ajax.put("phone",phone);
        return ajax;
    }

}
